/**
 * Filename: UpLoadService.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/17 16:06
 */
package com.github.postsanf.yinian.service;

import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

import com.github.postsanf.yinian.BaseIntentService;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.bean.YNUpLoadAttr;
import com.github.postsanf.yinian.bean.YNUpLoadStatus;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.db.DBManager;
import com.github.postsanf.yinian.db.YNUpImgKey;
import com.github.postsanf.yinian.db.YNUpProgress;
import com.github.postsanf.yinian.entity.YNStatusResponse;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SizeFormat;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.YNDoSecretUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.utils.AsyncRun;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 后台异步断点续传
 */
public class UpLoadService extends BaseIntentService {
    private volatile boolean isCancelled = false;
    private DBManager dbManager;
    private ExecutorService pool;
    private UploadManager mUpManager;
    private HashMap<Integer, YNUpLoadAttr> upLoadAttrManager;
    private boolean isFirst = true;     // 首次获取Token
    private HashMap<Integer, Boolean> isCancelManager;
    private Timer timer;
    private HashMap<Integer, List<YNUpImgKey>> upLoadImg;
    private List<String> netPic = new ArrayList<>();
    private List<String> changeNetPic = new ArrayList<>();
    private boolean local = false;
    private boolean modify = false;

    public UpLoadService() {
        super("UpLoadService");
    }

    private String url = null;

    @Override
    public void onCreate() {
        super.onCreate();
        dbManager = new DBManager(this);
        mUpManager = application.getUploadManager();
        isCancelManager = new HashMap<Integer, Boolean>();
        upLoadAttrManager = new HashMap<Integer, YNUpLoadAttr>();
        upLoadImg = new HashMap<Integer, List<YNUpImgKey>>();
        pool = Executors.newFixedThreadPool(2);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionPublishPhoto:
                    String uid = YNDoSecretUtils.doSecretStr(intent.getExtras().getString(ACTIONs.aUid));
                    String gid = YNDoSecretUtils.doSecretStr(intent.getExtras().getString(ACTIONs.aGid));
                    String gimid = intent.getExtras().getString(ACTIONs.aGimid);
                    int gtype = intent.getExtras().getInt(ACTIONs.aType);
                    int isPush = intent.getExtras().getInt(ACTIONs.aPush);
                    int isOfficial = intent.getExtras().getInt(ACTIONs.aIsOfficial);
                    String gname = intent.getExtras().getString(ACTIONs.aGname);
                    String content = intent.getExtras().getString(ACTIONs.aContent);
                    String eplace = intent.getExtras().getString(ACTIONs.aEplace);
                    boolean isPause = intent.getExtras().getBoolean(ACTIONs.aisPause);
                    int upismemorycard = intent.getExtras().getInt(ACTIONs.upismemorycard);
                    String uptags = intent.getExtras().getString(ACTIONs.uptags);
                    String upaudio = intent.getExtras().getString(ACTIONs.upaudio);
                    String upstorage = intent.getExtras().getString(ACTIONs.upstorage);
                    String upmemorytime = intent.getExtras().getString(ACTIONs.upmemorytime);
                    String upplace = intent.getExtras().getString(ACTIONs.upplace);
                    String upcardstyle = intent.getExtras().getString(ACTIONs.upcardstyle);
                    String upaudiotime = intent.getExtras().getString(ACTIONs.upaudiotime);
                    String upcoverUrl = intent.getExtras().getString(ACTIONs.upcoverUrl);
                    String upkey = "";
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
                    String uptime = sdf.format(new Date());
                    String upsize = "0";
                    long totalSize = 0;
                    if (SelectedImg.mSelectedImage.size() > 0) {
                        // UpProgress表
                        int upstatus = 0;
                        if (isPause) {
                            upstatus = 1;
                        }
                        YNUpProgress upProgress = new YNUpProgress(uid, gid, gimid, isOfficial, gname, gtype, content, eplace, uptime, upsize, SelectedImg.mSelectedImage.get(0), isPush, upstatus, upismemorycard, uptags, upaudio, upstorage, upmemorytime, upplace, upcardstyle, upaudiotime, upcoverUrl);
                        int upid = dbManager.addUpProgress(upProgress);
                        if (upid > 0) {
                            ArrayList<YNUpImgKey> upImgKeys = new ArrayList<YNUpImgKey>();
                            // 执行后台发布照片
                            for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                                String address = SelectedImg.mSelectedImage.get(i);
                                if (!address.startsWith("http")) {
                                    File uploadImgf = new File(address);
                                    long imgSize = uploadImgf.length();
                                    if (imgSize > 0) {
                                        totalSize += imgSize;
                                        YNUpImgKey upImgKey = new YNUpImgKey(upid, address, String.valueOf(imgSize), upkey);
                                        upImgKeys.add(upImgKey);
                                    }
                                    local = true;
                                } else {
                                    String[] split = address.split("/");
                                    String split1 = split[3].replace("?", ",");
                                    String[] split2 = split1.split(",");
                                    changeNetPic.add(split2[0]);
                                }
                            }
                            if (upImgKeys.size() > 0) {
                                dbManager.addUpImgKey(upImgKeys);
                                Log.i("xjs", "String.valueOf(totalSize)==>" + String.valueOf(totalSize));
                                dbManager.updateUpSizeById(upid, String.valueOf(totalSize));
                            }
                            SelectedImg.mSelectedImage.clear();
                        }
                        if (!isPause && local) {
                            isCancelManager.put(upid, false);
                            pool.execute(new UploadTask(upid, totalSize));
//                            new Thread(new UploadTask(upid, totalSize)).start();
                        } else {
                            UploadToYiNian(upid);
                            Intent intentProgress = new Intent(ACTIONs.actionUpdateProgress);
                            intentProgress.putExtra(ACTIONs.aUpId, upid);
                            intentProgress.putExtra(ACTIONs.aUpProgress, 100);
                            intentProgress.putExtra(ACTIONs.aUpSized, 100.0);
                            intentProgress.putExtra(ACTIONs.aUpSpeed, upstorage);
                            sendBroadcast(intent);
                        }
                        local = false;
                    }
                    break;
                case ACTIONs.actionCancelUpLoad:
                    Log.i("xjs", "ACTIONs.actionCancelUpLoad");
                    int cancelid = intent.getExtras().getInt(ACTIONs.aCancelId);
                    boolean isCancel = intent.getExtras().getBoolean(ACTIONs.aIsCancel);
                    switchIsUpload(cancelid, isCancel);
                    break;
                case ACTIONs.actionDeleteUp:
                    int deleteid = intent.getExtras().getInt(ACTIONs.aCancelId);
                    if (modify) {
                        modifyStatus(deleteid);
                    } else {
                        UploadToYiNian(deleteid);
                    }
                    break;
                case ACTIONs.actionDeleteUpload:
                    int cancelid2 = intent.getExtras().getInt(ACTIONs.aCancelId);
                    boolean isCancel2 = intent.getExtras().getBoolean(ACTIONs.aIsCancel);
                    isCancelManager.put(cancelid2, isCancel2);
                    dbManager.deleteUpProgressById(cancelid2);
                    Intent pIntent = new Intent(ACTIONs.actionDeleteList);
                    pIntent.putExtra(ACTIONs.aCancelId, cancelid2);
                    sendBroadcast(pIntent);
                    break;
                case ACTIONs.actionStartUp:
                    boolean modifyCon = SpUtils.getBoolean(UpLoadService.this, "modify");
                    if (modifyCon) {
                        modify = true;
                    }
                    startUp();
                    break;
                case ACTIONs.modifyStatus:
                    this.modify = true;
                    String userid = YNDoSecretUtils.doSecretStr(intent.getExtras().getString(ACTIONs.aUid));
                    String eid = intent.getStringExtra(ACTIONs.aEid);
                    String contentModify = intent.getExtras().getString(ACTIONs.aContent);
                    String place = intent.getExtras().getString(ACTIONs.aEplace);
                    String memorytime = intent.getExtras().getString(ACTIONs.upmemorytime);
                    String audio = intent.getExtras().getString(ACTIONs.upaudio);
                    String cover = intent.getExtras().getString(ACTIONs.upcoverUrl);
                    String tag = intent.getExtras().getString(ACTIONs.uptags);
                    String storage = intent.getExtras().getString(ACTIONs.upstorage);
                    String gnameModify = intent.getStringExtra(ACTIONs.upgname);
                    int upType = intent.getExtras().getInt(ACTIONs.aType);
                    boolean isPauseModify = intent.getExtras().getBoolean(ACTIONs.aisPause);
                    String picType = intent.getStringExtra(ACTIONs.picType);
                    String upkeyModify = "";
                    SimpleDateFormat timespf = new SimpleDateFormat("yyyy年MM月dd日");
                    String uptimeModify = timespf.format(new Date());
                    long totalSizeModify = 0;
                    if (SelectedImg.mSelectedImage.size() > 0) {
                        // UpProgress表
                        int upstatus = 0;
                        if (isPauseModify) {
                            upstatus = 1;
                        }
                        Log.d("yuhao", "gnameModify=" + gnameModify);
                        YNUpProgress upProgress = new YNUpProgress(userid, "", eid, 0, gnameModify, upType, 0, contentModify, place, uptimeModify, "0",
                                upstatus, SelectedImg.mSelectedImage.get(0), 0, tag, audio, storage, memorytime, "", picType, "", cover);
                        int upid = dbManager.addUpProgress(upProgress);
                        if (upid > 0) {
                            ArrayList<YNUpImgKey> upImgKeys = new ArrayList<YNUpImgKey>();
                            // 执行后台发布照片
                            for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                                String address = SelectedImg.mSelectedImage.get(i);
                                if (!address.startsWith("http")) {
                                    File uploadImgf = new File(address);
                                    long imgSize = uploadImgf.length();
                                    totalSizeModify += imgSize;
                                    YNUpImgKey upImgKey = new YNUpImgKey(upid, address, String.valueOf(imgSize), upkeyModify);
                                    upImgKeys.add(upImgKey);
                                    local = true;
                                } else {
                                    String[] split = address.split("/");
                                    String split1 = split[3].replace("?", ",");
                                    String[] split2 = split1.split(",");
                                    netPic.add(split2[0]);
                                }
                            }
                            if (upImgKeys.size() > 0) {
                                dbManager.addUpImgKey(upImgKeys);
                                dbManager.updateUpSizeById(upid, String.valueOf(totalSizeModify));
                            }
                            SelectedImg.mSelectedImage.clear();
                        }
                        if (!isPauseModify && local) {
                            pool.execute(new UploadTask(upid, totalSizeModify));
//                            new Thread(new UploadTask(upid, totalSizeModify)).start();
                        } else {
                            modifyStatus(upid);
                            Intent intentProgress = new Intent(ACTIONs.actionUpdateProgress);
                            intentProgress.putExtra(ACTIONs.aUpId, upid);
                            intentProgress.putExtra(ACTIONs.aUpProgress, 100);
                            intentProgress.putExtra(ACTIONs.aUpSized, 100.0);
                            intentProgress.putExtra(ACTIONs.aUpSpeed, storage);
                            sendBroadcast(intent);
                        }
                        local = false;
                    }
                    break;
                case ACTIONs.actionPublishElement:
                    Log.i("xjs", "actionPublishElement===》");
                    String euid = YNDoSecretUtils.doSecretStr(intent.getExtras().getString(ACTIONs.aUid));
                    String egid = YNDoSecretUtils.doSecretStr(intent.getExtras().getString(ACTIONs.aGid));
                    String econtent = intent.getExtras().getString(ACTIONs.aContent);
                    String eupaudio = intent.getExtras().getString(ACTIONs.upaudio);
                    String eupplace = intent.getExtras().getString(ACTIONs.upplace);
                    String upplacepic = intent.getExtras().getString(ACTIONs.upplacepic);
                    String upplaceLongitude = intent.getExtras().getString(ACTIONs.upplaceLongitude);
                    String upplaceLatitude = intent.getExtras().getString(ACTIONs.upplaceLatitude);
                    String uppeopleName = intent.getExtras().getString(ACTIONs.uppeopleName);
                    boolean eisPause = intent.getExtras().getBoolean(ACTIONs.aisPause);
                    String upmain = intent.getExtras().getString(ACTIONs.upmain);
                    String eupstorage = intent.getExtras().getString(ACTIONs.upstorage);
                    String upsource = intent.getExtras().getString(ACTIONs.upsource);
                    String upispush = "";
                    if (!StringUtils.isEmpty(intent.getExtras().getString("isPush")))
                        upispush = intent.getExtras().getString("isPush");
                    String VERIFYPICADDRESS = intent.getExtras().getString(CommonConstants.YNS_VERIFYPICADDRESS);
                    String TOTALNUM = intent.getExtras().getString(CommonConstants.YNS_TOTALNUM);
                    String TOTALMONEY = intent.getExtras().getString(CommonConstants.YNS_TOTALMONEY);
                    String eupkey = "";
                    String eupsize = "0";
                    long etotalSize = 0;
                    if (SelectedImg.mSelectedImage.size() > 0) {
                        int upstatus = 0;
                        if (eisPause) {
                            upstatus = 1;
                        }
                        YNUpProgress upProgress = new YNUpProgress(euid, egid, "", 789, "", 789, 789, econtent, "", "",
                                eupsize, upstatus, SelectedImg.mSelectedImage.get(0), 789,
                                "", eupaudio, eupstorage, "",
                                eupplace, "", "", "", upplacepic, upplaceLongitude, upplaceLatitude, uppeopleName, upmain, upsource, upispush, VERIFYPICADDRESS, TOTALNUM, TOTALMONEY);
                        int upid = dbManager.addUpProgress(upProgress);
                        Log.i("xjs", "actionPublishElement===2222222222》");
                        if (upid > 0) {
                            ArrayList<YNUpImgKey> upImgKeys = new ArrayList<YNUpImgKey>();
                            // 执行后台发布照片
                            for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                                String address = SelectedImg.mSelectedImage.get(i);
                                if (!address.startsWith("http")) {
                                    File uploadImgf = new File(address);
                                    long imgSize = uploadImgf.length();
                                    if (imgSize > 0) {
                                        etotalSize += imgSize;
                                        YNUpImgKey upImgKey = new YNUpImgKey(upid, address, String.valueOf(imgSize), eupkey);
                                        upImgKeys.add(upImgKey);
                                    }
                                    local = true;
                                } else {
                                    String[] split = address.split("/");
                                    String split1 = split[3].replace("?", ",");
                                    String[] split2 = split1.split(",");
                                    changeNetPic.add(split2[0]);
                                }
                            }
                            if (upImgKeys.size() > 0) {
                                dbManager.addUpImgKey(upImgKeys);
                                dbManager.updateUpSizeById(upid, String.valueOf(etotalSize));
                            }
                            SelectedImg.mSelectedImage.clear();
                        }
                        if (!eisPause && local) {
                            isCancelManager.put(upid, false);
                            pool.execute(new UploadTask(upid, etotalSize));
                        } else {
                            UploadToYiNian(upid);
                            Intent intentProgress = new Intent(ACTIONs.actionUpdateProgress);
                            intentProgress.putExtra(ACTIONs.aUpId, upid);
                            intentProgress.putExtra(ACTIONs.aUpProgress, 100);
                            intentProgress.putExtra(ACTIONs.aUpSized, 100.0);
                            intentProgress.putExtra(ACTIONs.aUpSpeed, etotalSize);
                            sendBroadcast(intent);
                        }
                        local = false;
                    }
                    break;
                case ACTIONs.actionPublishVideo:
                    Log.i("xjs", "actionPublishVideo===》");
                    String vuid = YNDoSecretUtils.doSecretStr(intent.getExtras().getString(ACTIONs.aUid));
                    String vgid = YNDoSecretUtils.doSecretStr(intent.getExtras().getString(ACTIONs.aGid));
                    String vcontent = intent.getExtras().getString(ACTIONs.aContent);
                    String vupstorage = intent.getExtras().getString(ACTIONs.upstorage);
                    String vcover = intent.getExtras().getString(ACTIONs.upcover);
                    String vtime = intent.getExtras().getString(ACTIONs.uptime);
                    boolean visPause = intent.getExtras().getBoolean(ACTIONs.aisPause);
                    String vsource = intent.getExtras().getString(ACTIONs.upsource);
                    String vupsize = "0";
                    String vupkey = "";
                    long vtotalSize = 0;
                    if (SelectedImg.mSelectedImage.size() > 0) {
                        int upstatus = 0;
                        if (visPause) {
                            upstatus = 1;
                        }
                        //video用upismemorycard=999判断
                        YNUpProgress upProgress = new YNUpProgress(vuid, vgid, "", 789, "", 789, 789, vcontent, "", "",
                                "", upstatus, vcover, 999,
                                "", "", vupstorage, "",
                                "", "", "", "", "", "", "", "", "", vsource, "", "", vcover, vtime);
                        int upid = dbManager.addUpProgress(upProgress);
                        Log.i("xjs", "actionPublishVideo===44444444444》");
                        if (upid > 0) {
                            ArrayList<YNUpImgKey> upImgKeys = new ArrayList<YNUpImgKey>();
                            // 执行后台发布照片
                            for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                                String address = SelectedImg.mSelectedImage.get(i);
                                if (!address.startsWith("http")) {
                                    File uploadImgf = new File(address);
                                    long imgSize = uploadImgf.length();
                                    if (imgSize > 0) {
                                        vtotalSize += imgSize;
                                        YNUpImgKey upImgKey = new YNUpImgKey(upid, address, String.valueOf(imgSize), vupkey);
                                        upImgKeys.add(upImgKey);
                                    }
                                    local = true;
                                } else {
                                    String[] split = address.split("/");
                                    String split1 = split[3].replace("?", ",");
                                    String[] split2 = split1.split(",");
                                    changeNetPic.add(split2[0]);
                                }
                            }
                            if (upImgKeys.size() > 0) {
                                dbManager.addUpImgKey(upImgKeys);
                                dbManager.updateUpSizeById(upid, String.valueOf(vtotalSize));
                            }
                            SelectedImg.mSelectedImage.clear();
                        }
                        if (!visPause && local) {
                            isCancelManager.put(upid, false);
                            pool.execute(new UploadTask(upid, vtotalSize));
                        } else {
                            UploadToYiNian(upid);
                            Intent intentProgress = new Intent(ACTIONs.actionUpdateProgress);
                            intentProgress.putExtra(ACTIONs.aUpId, upid);
                            intentProgress.putExtra(ACTIONs.aUpProgress, 100);
                            intentProgress.putExtra(ACTIONs.aUpSized, 100.0);
                            intentProgress.putExtra(ACTIONs.aUpSpeed, vtotalSize);
                            sendBroadcast(intent);
                        }
                        local = false;
                    }
                    break;
            }
        }
    }

    // 开启上传
    private void startUp() {
        // 获取上传列表 并开始上传待传照片到对应相册
        List<YNUpProgress> upProgresses = dbManager.queryUpProgressAll();
        for (int i = 0; i < upProgresses.size(); i++) {
            // 处于上传状态
            if (0 == upProgresses.get(i).upstatus) {
                int upid = upProgresses.get(i).id;
                long totalsize = Long.parseLong(upProgresses.get(i).upsize);
                pool.execute(new UploadTask(upid, totalsize));
//                new Thread(new UploadTask(upid, totalsize)).start();
            }
        }
    }

    // 上传并删除
    private void UploadToYiNian(final int id) {
        sendBroadcast(new Intent("uploadstartPd"));
        final YNUpProgress upInfos = dbManager.queryUpProgressById(id);
        List<String> qiniuKeys = dbManager.queryUpKeysById(id);
        String urlsto = getString(R.string.BASE_URL) + getString(R.string.ynUploadEvent);
        if (changeNetPic.size() != 0) {
            urlsto = getString(R.string.BASE_URL) + getString(R.string.ynTransferPhoto);
            url = urlsto;
            qiniuKeys.addAll(changeNetPic);
            changeNetPic.clear();
        }
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_ID, upInfos.upgid);
        mParam.put(CommonConstants.YNS_CONTENT, upInfos.upcontent);
        mParam.put(CommonConstants.YNS_PIC_ADDRESS, ReqUtils.list2String(qiniuKeys));
        if (!StringUtils.isEmpty(upInfos.upmain)) {
            urlsto = "https://api.zhuiyinanian.com/YinianProject/event/UploadEvent";
            mParam.put("userid", upInfos.upuid);
        } else {
            if (upInfos.upeplace != null)
                mParam.put(CommonConstants.YNS_EPLACE, upInfos.upeplace);
            mParam.put(CommonConstants.YNS_USER_ID, upInfos.upuid);
            mParam.put(CommonConstants.YNS_PIC_MODE, "private");
        }
        String upstorage = upInfos.upstorage;
        if (upInfos.upisofficial == 1 && upInfos.upismemorycard != 1) {
            //   投稿
            urlsto = getString(R.string.BASE_URL) + getString(R.string.ynTouGao);
            mParam.put(CommonConstants.YNS_SHOTTIME, "");
            mParam.put(CommonConstants.YNS_SHOTPLACE, "");
        } else if (upInfos.upisofficial == 1 && upInfos.upismemorycard == 1) {
            //  投稿官方相册记录卡片
            urlsto = getString(R.string.BASE_URL) + getString(R.string.ynUploadMemoryCardToOfficialAlbum);
            mParam.put(CommonConstants.YNS_TAGS, String.valueOf(upInfos.uptags));
            if (!StringUtils.isEmpty(upInfos.upaudio)) {
                mParam.put(CommonConstants.YNS_AUDIO, String.valueOf(upInfos.upaudio));
            }
            mParam.put(CommonConstants.YNS_MEMORYTIME, String.valueOf(upInfos.upmemorytime));
            mParam.put(CommonConstants.YNS_PLACE, String.valueOf(upInfos.upplace));
            mParam.put(CommonConstants.YNS_CARDSTYLE, String.valueOf(0));
            mParam.put(CommonConstants.YNS_AUDIOTIME, String.valueOf(0));
        } else if (upInfos.upismemorycard == 999) {
            //   上传视频===>
            urlsto = "https://api.zhuiyinanian.com/YinianProject/event/UploadShortVideo";
            mParam.put(CommonConstants.YNS_PIC_ADDRESS, "");
            mParam.put("address", ReqUtils.list2String(qiniuKeys));
            mParam.put("cover", upInfos.totalnum);
            mParam.put("time", upInfos.totalmoney);
            if (upInfos.upsource != null)
                mParam.put(CommonConstants.YNS_SOURCE, upInfos.upsource);
        } else {
            if (upInfos.uptype == 1) {
                //   官方相册上传照片
                urlsto = getString(R.string.BASE_URL) + getString(R.string.ynUploadOfficialAlbum);
                mParam.put(CommonConstants.YNS_SHOTTIME, "");
                mParam.put(CommonConstants.YNS_SHOTPLACE, "");
                mParam.put(CommonConstants.YNS_IS_PUSH, upInfos.uppush + "");
            }
            if (upInfos.upisofficial != 1 && upInfos.upismemorycard == 1) {
                //  投稿官方相册记录卡片
                urlsto = getString(R.string.BASE_URL) + getString(R.string.ynUploadMemoryCard);
                mParam.put(CommonConstants.YNS_TAGS, String.valueOf(upInfos.uptags));
                if (!StringUtils.isEmpty(upInfos.upaudio)) {
                    mParam.put(CommonConstants.YNS_AUDIO, String.valueOf(upInfos.upaudio));
                }
                mParam.put(CommonConstants.YNS_MEMORYTIME, String.valueOf(upInfos.upmemorytime));
                mParam.put(CommonConstants.YNS_PLACE, String.valueOf(upInfos.upplace));
                mParam.put(CommonConstants.YNS_CARDSTYLE, String.valueOf(0));
            } else if (upInfos.upismemorycard == 2) {
                //   投稿官方相册记录卡片;
                urlsto = getString(R.string.BASE_URL) + getString(R.string.ynUploadPostcard);
                if (!StringUtils.isEmpty(upInfos.upaudio)) {
                    mParam.put(CommonConstants.YNS_AUDIO, String.valueOf(upInfos.upaudio));
                }
                mParam.put(CommonConstants.YNS_AUDIOTIME, upInfos.upaudiotime);
                mParam.put(CommonConstants.YNS_MEMORYTIME, String.valueOf(upInfos.upmemorytime));
                mParam.put(CommonConstants.YNS_PLACE, String.valueOf(upInfos.upplace));
                mParam.put(CommonConstants.YNS_CARDSTYLE, String.valueOf(0));
                mParam.put(CommonConstants.YNS_COVERURL, upInfos.upcoverurl);
            } else {
                //上传新元素
//                Log.i("xjs", "上传新元素");
                if (!StringUtils.isEmpty(upInfos.verifypicaddress)) {
                    urlsto = "https://api.zhuiyinanian.com/YinianProject/event/UploadScanEvent";
                    mParam.put(CommonConstants.YNS_VERIFYPICADDRESS, upInfos.verifypicaddress);
                    mParam.put(CommonConstants.YNS_TOTALNUM, upInfos.totalnum);
                    mParam.put(CommonConstants.YNS_TOTALMONEY, upInfos.totalmoney);
                }
                mParam.put(CommonConstants.YNS_AUDIO, upInfos.upaudio);
                if (upInfos.upplace != null)
                    mParam.put(CommonConstants.YNS_PLACE, upInfos.upplace);
                if (upInfos.upplacepic != null)
                    mParam.put(CommonConstants.YNS_PLACEPIC, upInfos.upplacepic);
                if (upInfos.upplacelongitude != null)
                    mParam.put(CommonConstants.YNS_PLACELONGITUDE, upInfos.upplacelongitude);
                if (upInfos.upplacelatitude != null)
                    mParam.put(CommonConstants.YNS_PLACELATITUDE, upInfos.upplacelatitude);
                if (upInfos.uppeoplename != null)
                    mParam.put(CommonConstants.YNS_PEOPLENAME, upInfos.uppeoplename);
                if (upInfos.upmain != null)
                    mParam.put(CommonConstants.YNS_MAIN, upInfos.upmain);
                if (upInfos.upispush != null)
                    mParam.put(CommonConstants.YNS_IS_PUSH, upInfos.upispush);
                if (upInfos.upsource != null)
                    mParam.put(CommonConstants.YNS_SOURCE, upInfos.upsource);
            }
        }
        mParam.put(CommonConstants.YNS_STORAGE, upstorage);
//        Log.i("xjs", "urlsto===>" + urlsto);
        Log.i("xjs", "mpstring===>" + mParam.toString());
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNStatusResponse resStatus = gson.fromJson(s, YNStatusResponse.class);
//                        Log.i("xjs", "uploadsssssss==>" + s.toString());
                        if (ReqUtils.isSuccess(resStatus.getCode())) {
                            if (upInfos.upisofficial == 1 && upInfos.upismemorycard == 1) {
                                showToast("正在审核投稿");
                            }
                            if (resStatus.getData() != null) {
                                YNStatus mstatus = resStatus.getData().get(0);
                                YNSingleton.getInstance().clearCurStatus();
                                YNSingleton.getInstance().setCurStatus(mstatus);
//                                if (url != null && url.equals("https://api.zhuiyinanian.com/YinianProject/yinian/TransferPhoto")) {
//                                    String[] split = upInfos.upgimid.split(",");
//                                    for (int i = 0; i < split.length; i++) {
//                                        sendHuanXinMessage(split[i], upInfos.upismemorycard, mstatus);
//                                    }
//                                } else {
//                                    sendHuanXinMessage(upInfos.upgimid, upInfos.upismemorycard, mstatus);
//                                }
                                url = null;
                                // 通知动态更新
                                Intent mIntent = new Intent(ACTIONs.actionStatus);
                                mIntent.putExtra(ACTIONs.IsAdd, true);
                                mIntent.putExtra(ACTIONs.StatusId, mstatus.getEid());
                                sendBroadcast(mIntent);
                                sendBroadcast(new Intent(ACTIONs.actionAlbumInit));
                                sendBroadcast(new Intent(ACTIONs.actionGridWallUpdate));
                            }
                            // 删除数据
                            dbManager.deleteUpProgressById(id);
                            // 通知UpProgress删除列表
                            Intent pIntent = new Intent(ACTIONs.actionDeleteList);
                            pIntent.putExtra(ACTIONs.aCancelId, id);
                            sendBroadcast(pIntent);
                            File mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
                            if (mTempDir.exists()) {
                                mTempDir.delete();
                            }
                        } else {
                            showToast(resStatus.getMsg());
                        }
                        sendBroadcast(new Intent("uploadoverPd"));
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Log.i("xjs", "onFailure");
                        sendBroadcast(new Intent("uploadoverPd"));
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    public void modifyStatus(final int id) {
        final YNUpProgress upInfos = dbManager.queryUpProgressById(id);
        List<String> qiniuKeys = dbManager.queryUpKeysById(id);
        if (netPic.size() != 0) {
            qiniuKeys.addAll(netPic);
        }
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, upInfos.upuid);
        mParam.put(CommonConstants.YNS_EID, upInfos.upgimid);
        mParam.put(CommonConstants.YNS_PICTURE, ReqUtils.list2String(qiniuKeys));
        if (!upInfos.upcontent.equals("")) {
            mParam.put(CommonConstants.YNS_CONTENT, upInfos.upcontent);
        }
        if (!upInfos.upeplace.equals("")) {
            mParam.put(CommonConstants.YNS_PLACE, upInfos.upeplace);
        }
        if (!upInfos.upmemorytime.equals("")) {
            mParam.put(CommonConstants.YNS_MEMORYTIME, String.valueOf(upInfos.upmemorytime));
        }
        if (upInfos.upaudio != null) {
            mParam.put(CommonConstants.YNS_AUDIO, String.valueOf(upInfos.upaudio));
        }
        if (!upInfos.upcoverurl.equals("")) {
            mParam.put(CommonConstants.YNS_COVER, upInfos.upcoverurl);
        }
        if (!upInfos.uptags.equals("")) {
            mParam.put("tag", String.valueOf(upInfos.uptags));
        }
        mParam.put(CommonConstants.YNS_STORAGE, upInfos.upstorage);
        mParam.put(CommonConstants.YNS_TYPE, upInfos.upcardstyle);
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/yinian/ModifyEvent")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNStatusResponse resStatus = gson.fromJson(s, YNStatusResponse.class);
                        if (ReqUtils.isSuccess(resStatus.getCode())) {
                            if (resStatus.getMsg().equals("success")) {
                                // 通知动态修改
                                sendBroadcast(new Intent(ACTIONs.modifyStatus));
                                showToast("编辑成功...");
                            }
                            // 删除数据
                            dbManager.deleteUpProgressById(id);
                            // 通知UpProgress删除列表
                            Intent pIntent = new Intent(ACTIONs.actionDeleteList);
                            pIntent.putExtra(ACTIONs.aCancelId, id);
                            sendBroadcast(pIntent);
                            File mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
                            if (mTempDir.exists()) {
                                mTempDir.delete();
                            }
                        } else {
                            showToast(resStatus.getMsg());
                            SpUtils.put(UpLoadService.this, "modify", true);
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        SpUtils.put(UpLoadService.this, "modify", true);
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

//    private void sendHuanXinMessage(String gimid, int type, YNStatus mstatus) {
//        String title = null;
//        switch (type) {
//            case 0:
//                title = "上传了照片";
//                break;
//            case 1:
//                title = "发布了一张记录卡片";
//                break;
//            case 2:
//                title = "发布了一张语音图集";
//                break;
//        }
//        EMMessage message = EMMessage.createTxtSendMessage(TextBase64Util.encode(title), gimid);
//        if (message == null) {
//            return;
//        }
//        message.setChatType(EMMessage.ChatType.GroupChat);
//        YNUser ynUser = application.getCurUser();
//        message.setAttribute("type", String.valueOf(type));
//        message.setAttribute("accountName", ynUser.getUnickname());
//        message.setAttribute("img", ynUser.getUpic());
//        message.setAttribute("fristpic", mstatus.getEfirstpic());
//        message.setAttribute("eventId", mstatus.getEid());
//        EMClient.getInstance().chatManager().sendMessage(message);
//        if (!StringUtils.isEmpty(application.getCurgimid()) && application.getCurgimid().equals(gimid)) {
//            Intent intent = new Intent(ACTIONs.actionToChat);
//            intent.putExtra("gimid", gimid);
//            sendBroadcast(intent);
//        }
//    }

    class UploadTask implements Runnable {
        private int upId;
        private long totalSize;

        public UploadTask(int upId, long totalSize) {
            this.upId = upId;
            this.totalSize = totalSize;
        }

        @Override
        public void run() {
            isCancelManager.put(upId, false);
            handleUploadImg(upId, totalSize, isCancelled);
//            }
        }
    }

    // 主动获取Token  间隔30分钟
    private void doTokenPrepare() {
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // getToken();
                getPrivateSpaceUploadToken();
            }
        }, 300, 30 * 60 * 1000);
    }

    // 获取上传口令
//    private void getToken() {
//        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
//                .setMethod(HttpMethods.Post)
//                .setHttpListener(new HttpListener<String>(true, false, true) {
//                    @Override
//                    public void onSuccess(String s, Response<String> response) {
//                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
//                        if (ReqUtils.isSuccess(resToken.getCode())) {
//                            application.setUpToken(resToken.getData().get(0).getToken());
//                            if (isFirst) {
//                                isFirst = false;
//                            }
//                        } else {
//                            showToast(resToken.getMsg());
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(HttpException e, Response<String> response) {
//                        //  showToast(CommonConstants.YN_NET_LINK);
//                    }
//                });
//        liteHttp.executeAsync(req);
//    }

    private void getPrivateSpaceUploadToken() {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetPrivateSpaceUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            application.setUpToken(resToken.getData().get(0).getToken());
                            if (isFirst) {
                                isFirst = false;
                            }
                        } else {
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        //  showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    boolean handleUploadImgbbcccc = false;

    // 向UpProgressActivity发送上传进度信息
    public synchronized void handleUploadImg(int upId, long totalsize, boolean isCancelled) {
//        handleUploadImgbbcccc = isCancelled;
        Log.d("xjs", "handleUploadImg+bbcccc===>" + handleUploadImgbbcccc);
        if (isFirst) {
            doTokenPrepare();
            // 如果token无效2秒后自动上传
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            handleUploadImg(upId, totalsize, isCancelled);
            return;
        }
        // 获取已经上传图片的Size
        long uped = dbManager.getUpedSizeById(upId);
        // 记录该上传组的进度记录
        upLoadAttrManager.put(upId, new YNUpLoadAttr(totalsize, uped));
        // 获取对应ID的未获取key值得图片列表
        List<YNUpImgKey> upImgs = dbManager.queryNullKeyById(upId);
        upLoadImg.put(upId, upImgs);
        if (upImgs.size() > 0) {
//            for (int i = 0; i < upImgs.size(); i++) {
//                upLoadAttrManager.get(upId).upInfo.put(upImgs.get(i).id, new YNUpLoadStatus(0, 0, Long.parseLong(upImgs.get(i).upimgsize)));
//                upload2qiniu(upImgs.get(i).id, upImgs.get(i).upid, upImgs.get(i).upaddress);
//            }
            publishImg(0, upId);
        } else {
//            Log.d("yuhao", "上传中_handleUploadImg");
            if (modify) {
                modifyStatus(upId);
            } else {
                UploadToYiNian(upId);
            }
        }
    }

    private void publishImg(int i, int upId) {
        if (i < upLoadImg.get(upId).size()) {
            upLoadAttrManager.get(upId).upInfo.put(upLoadImg.get(upId).get(i).id, new YNUpLoadStatus(0, 0, Long.parseLong(upLoadImg.get(upId).get(i).upimgsize)));
            upload2qiniu(upLoadImg.get(upId).get(i).id, upLoadImg.get(upId).get(i).upid, upLoadImg.get(upId).get(i).upaddress, i);
        }
    }

    Handler subHandler2 = null;

    // 上传至七牛云
    private void upload2qiniu(final int imgid, final int upid, String imgAddress, final int curNum) {
//        Log.i("xjs", "upload2qiniu+bbcccc===>" + bbcccc);
        if (this.mUpManager == null) {
            return;
        }
        File uploadFile = new File(imgAddress);
        upLoadAttrManager.get(upid).upInfo.get(imgid).uploadLastTimePoint = System.currentTimeMillis();
        upLoadAttrManager.get(upid).upInfo.get(imgid).uploadLastOffset = 0;
        String prefix = imgAddress.substring(imgAddress.lastIndexOf(".") + 1);
        // 为图片重命名
        String imgName = UUID.randomUUID().toString() + "." + prefix;
        this.mUpManager.put(uploadFile, imgName, application.getUpToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo respInfo, JSONObject jsonData) {
                        if (respInfo.isOK()) {
                            try {
                                String fileKey = jsonData.getString("key");
                                // 更新图片key
                                dbManager.updateUpKey(imgid, fileKey);
                                upLoadAttrManager.get(upid).uploadUpedSize += upLoadAttrManager.get(upid).upInfo.get(imgid).uploadFileLength;
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            showLog("----------------------------七牛云上传图片失败---------------------------------");
                        }
//                        if (!bbcccccc) {
                        publishImg(curNum + 1, upid);
//                        }
                    }
                }, new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            @Override
                            public void progress(String key, double percent) {
                                updateUpProgressStatus(upid, imgid, percent);
                            }
                        }, new UpCancellationSignal() {
                    @Override
                    public boolean isCancelled() {
//                        boolean bbCancel = isCancelManager.get(upid);
//                        Looper.prepare();
//                        subHandler2 = new Handler() {
//                            @Override
//                            public void handleMessage(Message msg) {
//                                if (msg.what == 1) {
//                                    handleUploadImgbbcccc = true;
//                                } else if (msg.what == 2) {
//                                    handleUploadImgbbcccc = false;
//                                }
//                                Log.i("xjs", "isCancelled+upload2qiniubbcccccc===>" + handleUploadImgbbcccc);
//                            }
//                        };
//                        Looper.loop();
                        return false;
                    }
                }));
    }

    // 点击暂停按钮来更改切换是否上传
    public void switchIsUpload(int upid, boolean isCancel) {
        isCancelManager.put(upid, isCancel);
        dbManager.updateUpStatus(upid, isCancel);
//        Log.i("xjs", "upid===>" + upid);
        Log.i("xjs", "isCancel===>" + isCancel);
        YNUpProgress upProgress = dbManager.queryUpProgressById(upid);
        if (!isCancel) {
            isCancelled = false;
            pool.execute(new UploadTask(upid, Long.parseLong(upProgress.upsize)));
//            new Thread(new UploadTask(upid, Long.parseLong(upProgress.upsize))).start();
        } else {
            Log.v("xjs", "shutdownNow===>");
            isCancelled = true;
//            new Thread(new UploadTask(upid, Long.parseLong(upProgress.upsize))).start();
//            pool.execute(new UploadTask(upid, Long.parseLong(upProgress.upsize)));
        }
    }

    final long awaitTime = 1 * 1000;

    private Handler handler = new Handler();

    // 更新上传进度
    private void updateUpProgressStatus(final int upId, int imgid, final double percentage) {
        long now = System.currentTimeMillis();
        long deltaTime = now - upLoadAttrManager.get(upId).upInfo.get(imgid).uploadLastTimePoint;
        final long currentOffset = (long) (percentage * upLoadAttrManager.get(upId).upInfo.get(imgid).uploadFileLength);
        long deltaSize = currentOffset - upLoadAttrManager.get(upId).upInfo.get(imgid).uploadLastOffset;
        // 设置0.3s更新一次进度
        if (percentage < 1 && deltaTime <= 500) {
            return;
        }
        // 计算上载速度
        final String speed = SizeFormat.formatSpeed(deltaSize, deltaTime);
        // 重置时间点和进度偏移
        upLoadAttrManager.get(upId).upInfo.get(imgid).uploadLastTimePoint = now;
        upLoadAttrManager.get(upId).upInfo.get(imgid).uploadLastOffset = currentOffset;
        final int progress = (int) ((upLoadAttrManager.get(upId).uploadUpedSize + currentOffset) * 100 / upLoadAttrManager.get(upId).uploadTotalSize);
        if (progress >= 100) {
            Log.d("yuhao", "progress=" + progress);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (modify) {
                        modifyStatus(upId);
                    } else {
                        UploadToYiNian(upId);
                    }
                }
            }, 50);
        }
        // 通知更新上传进度显示
        AsyncRun.run(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent(ACTIONs.actionUpdateProgress);
                intent.putExtra(ACTIONs.aUpId, upId);
                intent.putExtra(ACTIONs.aUpProgress, progress);
                intent.putExtra(ACTIONs.aUpSized, upLoadAttrManager.get(upId).uploadUpedSize + currentOffset);
                intent.putExtra(ACTIONs.aUpSpeed, speed);
                sendBroadcast(intent);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 释放数据库资源
//        dbManager.closeDB();

    }
}
